import { ChangeDetectionStrategy, Component, OnDestroy, OnInit, ViewChild } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Subject } from 'rxjs';
import { debounceTime, distinctUntilChanged, takeUntil } from 'rxjs/operators';
import { TreetableComponent, TreeTableNode } from '@iux/live';

@Component({
  selector: 'app-filter-selected',
  templateUrl: './filter-selected.component.html',
  changeDetection: ChangeDetectionStrategy.OnPush,
})
export class FilterSelectedComponent implements OnInit, OnDestroy {
  data: TreeTableNode[];
  selection: TreeTableNode[];
  value;
  search$ = new Subject<string>();
  destroy$ = new Subject<void>();
  @ViewChild(TreetableComponent, { static: false }) lvTable: TreetableComponent;
  constructor(private http: HttpClient) {}

  ngOnInit() {
    this.initAsyncData();
  }

  ngOnDestroy(): void {
    this.destroy$.next();
    this.destroy$.complete();
  }

  initAsyncData() {
    this.http.get('showcase/tree-table/filter-selected/data.json', { params: { $prefix: 'none' } }).subscribe((res: TreeTableNode[]) => {
      this.data = res;
    });

    this.searchSubscribe();
  }

  selectionChange(source) {
    console.log('selection change', source);
  }

  clearSelection() {
    this.lvTable.clearSelection();
  }

  stateChange(source: { [key: string]: any }) {
    console.log('state change:', source);
  }

  updateSearch(e: any) {
    this.value = e;
    this.search$.next(e);
  }

  searchSubscribe() {
    this.search$.pipe(debounceTime(300), distinctUntilChanged(), takeUntil(this.destroy$)).subscribe(value => {
      this.filterByName(value);
    });
  }

  filterByName(value: string) {
    this.lvTable.filter({ key: 'data.id', value, filterMode: 'contains' });
  }
}
